using System;
using System.ComponentModel;
using System.ComponentModel.Design;

namespace Ferpect.GameComponents.Design
{
    public class TypeOfTypeConverter<T> : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (typeof(Type).IsAssignableFrom(sourceType))
            {
                return true;
            }
            if (sourceType == typeof(string))
            {
                return true;
            }
            return base.CanConvertFrom(context, sourceType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            if (value == null)
            {
                return null;
            }
            if (value is Type)
            {
                return value;
            }
            string stringValue = (string)value;

            if (stringValue.Length == 0)
            {
                return null;
            }
            ITypeResolutionService typeResolution = context.GetService(typeof(ITypeResolutionService)) as ITypeResolutionService;
            return typeResolution.GetType(stringValue);
        }

        public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
        {
            if (context != null)
            {
                ITypeDiscoveryService typeDiscovery = context.GetService(typeof(ITypeDiscoveryService)) as ITypeDiscoveryService;
                if (typeDiscovery != null)
                {
                    return new StandardValuesCollection(typeDiscovery.GetTypes(typeof(T), true));
                }
            }
            return base.GetStandardValues(context);
        }

        public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
        {
            return true;
        }
    }
}